package com.yami.shop.cp.comment.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yami.shop.bean.app.dto.ShopCartItemDto;
import com.yami.shop.bean.app.dto.ShopCartOrderDto;
import com.yami.shop.bean.enums.OrderStatus;
import com.yami.shop.bean.enums.OrderType;
import com.yami.shop.bean.enums.TransportChargeType;
import com.yami.shop.bean.event.SubmitScoreOrderEvent;
import com.yami.shop.bean.model.*;
import com.yami.shop.bean.param.SkuRetailParam;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.i18n.LanguageEnum;
import com.yami.shop.common.util.Arith;
import com.yami.shop.common.util.Json;
import com.yami.shop.cp.comment.dto.CollaborativePurchaseShopCartItemDto;
import com.yami.shop.cp.comment.enums.CollaborativePurchaseBasketEnum;
import com.yami.shop.cp.comment.model.CollaborativePurchaseAddr;
import com.yami.shop.cp.comment.model.CollaborativePurchaseBasket;
import com.yami.shop.cp.comment.param.CPOrderParam;
import com.yami.shop.cp.comment.service.CPOrderService;
import com.yami.shop.cp.comment.service.CollaborativePurchaseAddrService;
import com.yami.shop.cp.comment.service.CollaborativePurchaseBasketService;
import com.yami.shop.dao.*;
import com.yami.shop.delivery.comment.model.Transfee;
import com.yami.shop.delivery.comment.model.TransfeeFree;
import com.yami.shop.delivery.comment.model.Transport;
import com.yami.shop.delivery.comment.service.TransportService;
import com.yami.shop.service.OrderItemService;
import com.yami.shop.service.ProductService;
import com.yami.shop.service.SkuService;
import lombok.AllArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class CPOrderServiceImpl implements CPOrderService {

    private CollaborativePurchaseBasketService collaborativePurchaseBasketService;
    private final Snowflake snowflake;
    private final ProductMapper productMapper;
    private final ProductService productService;
    private final SkuMapper skuMapper;
    private final SkuService skuService;
    private final OrderMapper orderMapper;
    private final OrderSettlementMapper orderSettlementMapper;
    private TransportService transportService;
    private CollaborativePurchaseAddrService collaborativePurchaseAddrService;
    private final OrderLangMapper orderlangMapper;
    private final OrderItemService orderItemService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<Order> submit(String userId, CPOrderParam cpOrderParam) {

        // 组装获取用户提交的购物车商品项
        List<CollaborativePurchaseShopCartItemDto> shopCartItemsDb = collaborativePurchaseBasketService.getShopCartItemsByCollaborativePurchaseIdAndStatus(cpOrderParam.getCollaborativePurchaseId(), CollaborativePurchaseBasketEnum.SUBMIT.getValue());

        // 获取用户地址
        CollaborativePurchaseAddr cpAddr = collaborativePurchaseAddrService.getOne(new LambdaQueryWrapper<CollaborativePurchaseAddr>().eq(CollaborativePurchaseAddr::getCollaborativePurchaseId, cpOrderParam.getCollaborativePurchaseId()));

        if (CollectionUtil.isEmpty(shopCartItemsDb)) {
            // 请选择您需要的商品加入购物车
            throw new YamiShopBindException("yami.selelct.items");
        }


        // 根据店铺ID划分item
        Map<Long, List<CollaborativePurchaseShopCartItemDto>> shopCartMap = shopCartItemsDb.stream().collect(Collectors.groupingBy(CollaborativePurchaseShopCartItemDto::getShopId));

        // 订单商品参数
        List<ShopCartOrderDto> shopCartOrders = new ArrayList<>();

        // 购物车id集合
        List<Long> basketIds = new ArrayList<>();
        // 商品skuid为key 需要更新的sku为value的map
        Map<Long, Sku> skuStocksMap = new HashMap<>(16);
        // 商品productid为key 需要更新的product为value的map
        Map<Long, Product> prodStocksMap = new HashMap<>(16);
        List<SkuRetailParam> skuRetailParams = new ArrayList<>();


        List<Order> orderList = new ArrayList<>();
        for (Long shopId : shopCartMap.keySet()) {
            ShopCartOrderDto shopCartOrderDto = new ShopCartOrderDto();
            shopCartOrderDto.setShopId(shopId);
            shopCartOrderDto.setShopName(shopCartMap.get(shopId).get(0).getShopName());
            buildOrder(shopId,shopCartMap.get(shopId),skuStocksMap,prodStocksMap,userId,basketIds,skuRetailParams,cpOrderParam,cpAddr,orderList);
        }


        // 修改购物车的商品信息
        if (!basketIds.isEmpty()) {
            for (Long basketId : basketIds) {
                collaborativePurchaseBasketService.update(new LambdaUpdateWrapper<CollaborativePurchaseBasket>()
                        .set(CollaborativePurchaseBasket::getStatus, "2")
                        .eq(CollaborativePurchaseBasket::getCollaborativePurchaseBasketId, basketId));
            }
        }

        // 更新sku库存
        skuStocksMap.forEach((key, sku) -> {
            if (skuMapper.updateStocks(sku) == 0) {
                skuService.removeSkuCacheBySkuIdAndLang(sku.getSkuId(), sku.getProdId(), LanguageEnum.LANGUAGE_ZH_CN.getLang());
                skuService.removeSkuCacheBySkuIdAndLang(sku.getSkuId(), sku.getProdId(), LanguageEnum.LANGUAGE_EN.getLang());
                productService.removeProdCacheByProdId(sku.getProdId(), LanguageEnum.LANGUAGE_ZH_CN.getLang());
                productService.removeProdCacheByProdId(sku.getProdId(), LanguageEnum.LANGUAGE_EN.getLang());
                // 商品库存不足
                String prodMsg = I18nMessage.getMessage("yami.product");
                String msg = I18nMessage.getMessage("yami.insufficient.inventory");
                throw new YamiShopBindException(prodMsg + "[" + sku.getProdName() + "]" + msg);
            }
        });

        // 更新商品库存
        prodStocksMap.forEach((prodId, prod) -> {
            if (productMapper.updateStocks(prod) == 0) {
                productService.removeProdCacheByProdId(prodId, LanguageEnum.LANGUAGE_ZH_CN.getLang());
                productService.removeProdCacheByProdId(prodId, LanguageEnum.LANGUAGE_EN.getLang());
                // 商品库存不足
                String prodMsg = I18nMessage.getMessage("yami.product");
                String msg = I18nMessage.getMessage("yami.insufficient.inventory");
                throw new YamiShopBindException(prodMsg + "[" + prod.getProdName() + "]" + msg);
            }
        });

        // 插入订单
        orderList.forEach(order -> orderMapper.insert(order));
        // 保存订单语言表
        orderlangMapper.insertBatchOrderLang(orderList);
        List<OrderItem> orderItems = orderList.stream().flatMap(order -> order.getOrderItems().stream()).collect(Collectors.toList());
        // 插入订单项，返回主键
        orderItemService.insertBatchOrderItem(orderItems);
        return orderList;

    }

    private void buildOrder(Long shopId, List<CollaborativePurchaseShopCartItemDto> collaborativePurchaseShopCartItemDtos,
                            Map<Long, Sku> skuStocksMap, Map<Long, Product> prodStocksMap, String userId, List<Long> basketIds,
                            List<SkuRetailParam> skuRetailParams, CPOrderParam cpOrderParam, CollaborativePurchaseAddr cpAddr, List<Order> orderList) {
        Date now = new Date();


        // 使用雪花算法生成的订单号
        String orderNumber = String.valueOf(snowflake.nextId());

        // 订单商品名称
        StringBuilder orderProdName = new StringBuilder(100);

        // 订单商品中文名称
        StringBuilder orderProdNameCn = new StringBuilder(100);

        // 订单商品英文名称
        StringBuilder orderProdNameEn = new StringBuilder(100);

        List<OrderItem> orderItems = new ArrayList<>();
        // 构建订单项并获取预售时间
        buildOrderItem(shopId, collaborativePurchaseShopCartItemDtos, skuStocksMap, prodStocksMap, orderNumber, userId, orderProdName, orderProdNameCn, orderProdNameEn, orderItems, basketIds, skuRetailParams);

        //中英文
        orderProdName = new StringBuilder(orderProdName.subSequence(0, Math.min(orderProdName.length() - 1, 100)));
        orderProdNameCn = new StringBuilder(orderProdNameCn.subSequence(0, Math.min(orderProdNameCn.length() - 1, 100)));
        orderProdNameEn = new StringBuilder(orderProdNameEn.subSequence(0, Math.min(orderProdNameEn.length() - 1, 100)));
        if (orderProdName.lastIndexOf(StrUtil.COMMA) == orderProdName.length() - 1) {
            orderProdName.deleteCharAt(orderProdName.length() - 1);
        }
        if (orderProdNameCn.lastIndexOf(StrUtil.COMMA) == orderProdNameCn.length() - 1) {
            orderProdNameCn.deleteCharAt(orderProdNameCn.length() - 1);
        }
        if (orderProdNameEn.lastIndexOf(StrUtil.COMMA) == orderProdNameEn.length() - 1) {
            orderProdNameEn.deleteCharAt(orderProdNameEn.length() - 1);
        }


        double actualTotal = 0.0;
        double total = 0.0;
        int totalCount = 0;


        for (CollaborativePurchaseShopCartItemDto collaborativePurchaseShopCartItemDto : collaborativePurchaseShopCartItemDtos) {
            total = Arith.add(collaborativePurchaseShopCartItemDto.getProductTotalAmount(), total);
            actualTotal = Arith.add(collaborativePurchaseShopCartItemDto.getProductTotalAmount(), actualTotal);
            totalCount = totalCount + collaborativePurchaseShopCartItemDto.getProdCount();

        }
        List<CollaborativePurchaseShopCartItemDto> notTransPortList = removeNotTransPort(collaborativePurchaseShopCartItemDtos);
        double freightAmount = repeatListTransfee(notTransPortList,cpAddr);

        // 订单信息
        com.yami.shop.bean.model.Order order = new com.yami.shop.bean.model.Order();
        order.setShopId(shopId);
        order.setOrderNumber(orderNumber);
        // 订单商品名称
        order.setProdName(orderProdName.toString());
        order.setProdNameCn(orderProdNameCn.toString());
        order.setProdNameEn(orderProdNameEn.toString());
        // 用户id
        order.setUserId(userId);
        // 商品总额
        order.setTotal(total);
        // 实际总额
        order.setActualTotal(actualTotal);
        order.setStatus(OrderStatus.UNPAY.value());
        order.setUpdateTime(now);
        order.setCreateTime(now);
        order.setIsPayed(0);
        order.setDeleteStatus(0);
        order.setProductNums(totalCount);
        order.setReduceAmount(Arith.sub(total, actualTotal));
        order.setFreightAmount(freightAmount);
        order.setOrderType(OrderType.ORDINARY.value());
        order.setOrderItems(orderItems);
        order.setDvyType(cpOrderParam.getDvyType());
        order.setReceiverName(cpAddr.getReceiver());
        order.setReceiverMobile(cpAddr.getMobile());
        order.setAddrOrderId(cpAddr.getId());

        order.setChangeAmountVersion(0);
        order.setCollaborativePurchaseId(cpOrderParam.getCollaborativePurchaseId());
        orderList.add(order);
        // 插入订单结算表
        OrderSettlement orderSettlement = new OrderSettlement();
        orderSettlement.setUserId(userId);
        orderSettlement.setIsClearing(0);
        orderSettlement.setCreateTime(now);
        orderSettlement.setOrderNumber(orderNumber);
        orderSettlement.setPayAmount(order.getActualTotal());
        orderSettlement.setPayStatus(0);
        orderSettlement.setVersion(0);
        orderSettlement.setPayScore(0);
        orderSettlement.setChangeAmountVersion(order.getChangeAmountVersion());
        orderSettlementMapper.insert(orderSettlement);
    }

    private void buildOrderItem(Long shopId, List<CollaborativePurchaseShopCartItemDto> collaborativePurchaseShopCartItemDtos,
                                Map<Long, Sku> skuStocksMap, Map<Long, Product> prodStocksMap, String orderNumber, String userId,
                                StringBuilder orderProdName, StringBuilder orderProdNameCn, StringBuilder orderProdNameEn,
                                List<OrderItem> orderItems, List<Long> basketIds, List<SkuRetailParam> skuRetailParams) {
        Date now = new Date();

        for (CollaborativePurchaseShopCartItemDto shopCartItem : collaborativePurchaseShopCartItemDtos) {
            Sku sku = checkAndGetSku(shopCartItem.getSkuId(), shopCartItem, skuStocksMap);
            Product product = checkAndGetProd(shopCartItem.getProdId(), shopCartItem, prodStocksMap);
            OrderItem orderItem = new OrderItem();
            orderItem.setShopId(shopId);
            orderItem.setOrderNumber(orderNumber);
            orderItem.setSkuId(sku.getSkuId());
            orderItem.setProdId(sku.getProdId());
            orderItem.setSkuName(sku.getSkuName());
            orderItem.setProdCount(shopCartItem.getProdCount());
            orderItem.setProdName(sku.getProdName());
            // 保存中英文名称
            orderItem.setProdNameCn(shopCartItem.getProdNameCn());
            orderItem.setProdNameEn(shopCartItem.getProdNameEn());
            orderItem.setPic(StrUtil.isBlank(sku.getPic()) ? product.getPic() : sku.getPic());
            orderItem.setPrice(shopCartItem.getPrice());
            orderItem.setUserId(userId);
            orderItem.setProductTotalAmount(shopCartItem.getProductTotalAmount());
            orderItem.setRecTime(now);
            orderItem.setCommSts(0);
            orderItem.setBasketDate(shopCartItem.getBasketDate());
            //平台的补贴优惠金额
            orderItem.setPlatformShareReduce(shopCartItem.getPlatformShareReduce());
            // 实际订单项支付金额
            orderItem.setActualTotal(shopCartItem.getActualTotal());
            // 分摊优惠金额
            orderItem.setShareReduce(shopCartItem.getShareReduce());
            orderProdName.append(orderItem.getProdName()).append(StrUtil.COMMA);
            orderProdNameCn.append(orderItem.getProdNameCn()).append(StrUtil.COMMA);
            orderProdNameEn.append(orderItem.getProdNameEn()).append(StrUtil.COMMA);
            //推广员卡号
            orderItem.setDistributionCardNo(shopCartItem.getDistributionCardNo());
            //使用积分价格
            orderItem.setUseScore(shopCartItem.getScorePrice());
            orderItem.setChangeAmountVersion(0);
            orderItems.add(orderItem);
            if (shopCartItem.getCollaborativePurchaseBasketId() != null && shopCartItem.getCollaborativePurchaseBasketId() != 0) {
                basketIds.add(shopCartItem.getCollaborativePurchaseBasketId());
            }
            if (Objects.equals(1, product.getIsCompose())) {
                SkuRetailParam skuRetailParam = new SkuRetailParam();
                skuRetailParam.setShopId(shopId);
                skuRetailParam.setProdId(product.getProdId());
                skuRetailParam.setSkuId(sku.getSkuId());
                skuRetailParam.setSkuNums(shopCartItem.getProdCount());
                skuRetailParam.setSkuName(sku.getProdName());
                skuRetailParam.setOrderNumber(orderNumber);
                skuRetailParams.add(skuRetailParam);
            }
        }
    }

    @SuppressWarnings({"Duplicates"})
    private Sku checkAndGetSku(Long skuId, CollaborativePurchaseShopCartItemDto shopCartItem, Map<Long, Sku> skuStocksMap) {
        // 获取sku信息
        Sku sku = skuService.getSkuBySkuId(skuId, I18nMessage.getDbLang());
        if (sku == null) {
            // 购物车包含无法识别的商品
            throw new YamiShopBindException("yami.contains.unrecognized.items");
        }

        if (sku.getStatus() != 1) {
            // 商品已下架
            String message = I18nMessage.getMessage("yami.product");
            String takeOff = I18nMessage.getMessage("yami.shopCart.take.off");
            throw new YamiShopBindException(message + "[" + sku.getProdName() + "]" + takeOff);
        }
        // -1为无限库存
        if (sku.getStocks() != -1 && shopCartItem.getProdCount() > sku.getStocks()) {
            // 商品库存不足
            String prodMsg = I18nMessage.getMessage("yami.product");
            String msg = I18nMessage.getMessage("yami.insufficient.inventory");
            throw new YamiShopBindException(prodMsg + "[" + sku.getProdName() + "]" + msg);
        }

        if (sku.getStocks() != -1) {
            Sku mapSku = new Sku();
            mapSku.setProdId(sku.getProdId());
            // 这里的库存是改变的库存
            mapSku.setStocks(shopCartItem.getProdCount());
            mapSku.setSkuId(sku.getSkuId());
            mapSku.setProdName(sku.getProdName());
            skuStocksMap.put(sku.getSkuId(), mapSku);
        }
        return sku;
    }

    @SuppressWarnings({"Duplicates"})
    private Product checkAndGetProd(Long prodId, CollaborativePurchaseShopCartItemDto shopCartItem, Map<Long, Product> prodStocksMap) {
        Product product = productService.getProductByProdId(prodId, I18nMessage.getDbLang());
        if (product == null) {
            // 购物车包含无法识别的商品
            throw new YamiShopBindException("yami.contains.unrecognized.items");
        }

        if (product.getStatus() != 1) {
            String message = I18nMessage.getMessage("yami.product");
            String takeOff = I18nMessage.getMessage("yami.shopCart.take.off");
            // 商品已下架
            throw new YamiShopBindException(message + "[" + product.getProdName() + "]" + takeOff);
        }

        // 商品需要改变的库存
        Product mapProduct = prodStocksMap.get(prodId);

        if (mapProduct == null) {
            mapProduct = new Product();
            mapProduct.setTotalStocks(0);
            mapProduct.setProdId(prodId);
            mapProduct.setProdName(product.getProdName());

        }

        if (product.getTotalStocks() != -1) {
            mapProduct.setTotalStocks(mapProduct.getTotalStocks() + shopCartItem.getProdCount());
            prodStocksMap.put(product.getProdId(), mapProduct);
        }

        // -1为无限库存
        if (product.getTotalStocks() != -1 && mapProduct.getTotalStocks() > product.getTotalStocks()) {
            // 商品库存不足
            String prodMsg = I18nMessage.getMessage("yami.product");
            String msg = I18nMessage.getMessage("yami.insufficient.inventory");
            throw new YamiShopBindException(prodMsg + "[" + product.getProdName() + "]" + msg);
        }

        return product;
    }

    /**
     * 计算出运费模板重复的订单运费
     *
     * @param productItems 运费模板是重复的订单
     * @param userAddr
     * @return
     */
    private Double repeatListTransfee(List<CollaborativePurchaseShopCartItemDto> productItems, CollaborativePurchaseAddr userAddr) {

        if (Objects.isNull(userAddr)) {
            return 0.0;
        }
        // 重复订单的运费
        double transportfee = 0.0;
        if (CollectionUtils.isEmpty(productItems)) {
            return 0.0;
        }
        if (productItems.size() >= 1) {
            // 获取第一个订单，将订单的重量体积和件数求和，加给第一个订单
            CollaborativePurchaseShopCartItemDto shopCartItemDto = productItems.get(0);
            Product productFirst = productService.getProductByProdId(productItems.get(0).getProdId(), I18nMessage.getDbLang());

            Sku skuOne = skuService.getSkuBySkuId(productItems.get(0).getSkuId(), I18nMessage.getDbLang());
            // 商品的件数 (总的件数)
            Integer prodCount = productItems.get(0).getProdCount();
            // 商品的重量
            double weight = skuOne.getWeight() == null ? 0 : skuOne.getWeight();
            // 总的重量
            double pieceWeight = Arith.mul(weight, prodCount);
            // 商品的体积
            double volume = skuOne.getVolume() == null ? 0 : skuOne.getVolume();
            // 总的体积
            double pieceVolume = Arith.mul(volume, productItems.get(0).getProdCount());

            // 商品总金额
            Double productTotalAmount = productItems.get(0).getProductTotalAmount();

            for (int i = 1; i < productItems.size(); i++) {
                // 商品的件数
                Integer prodCountI = productItems.get(i).getProdCount();
                prodCount += prodCountI;
                // 获取商品
                Product product = productService.getProductByProdId(productItems.get(i).getProdId(), I18nMessage.getDbLang());
                Sku sku = skuService.getSkuBySkuId(productItems.get(i).getSkuId(), I18nMessage.getDbLang());
                // 商品的重量
                double weightSku = sku.getWeight() == null ? 0 : sku.getWeight();
                pieceWeight = Arith.add(pieceWeight, Arith.mul(weightSku, prodCountI));

                // 商品的体积
                double volumeSku = skuOne.getVolume() == null ? 0 : skuOne.getVolume();
                pieceVolume = Arith.add(pieceVolume, Arith.mul(volumeSku, prodCountI));
                // 商品总金额
                productTotalAmount = Arith.add(productTotalAmount, productItems.get(i).getProductTotalAmount() == null ? 0.0 : productItems.get(i).getProductTotalAmount());

            }


            // 用户所在区域的id
            Long areaId = userAddr.getAreaId();

            //找出该产品的运费项  运费模板
            Transport transport = transportService.getTransportAndAllItems(productFirst.getDeliveryTemplateId());
            //商家把运费模板删除
            if (transport == null) {
                return 0.0;
            }

            // 用于计算运费的件数
            double piece = 0.0;

            if (Objects.equals(TransportChargeType.COUNT.value(), transport.getChargeType())) {
                // 按件数计算运费
                piece = Double.valueOf(prodCount);
            } else if (Objects.equals(TransportChargeType.WEIGHT.value(), transport.getChargeType())) {
                // 按重量计算运费
                piece = Double.valueOf(pieceWeight);
            } else if (Objects.equals(TransportChargeType.VOLUME.value(), transport.getChargeType())) {
                // 按体积计算运费
                piece = Double.valueOf(pieceVolume);
            }
            //如果有包邮的条件
            if (transport.getHasFreeCondition() == 1) {
                // 获取所有的包邮条件
                List<TransfeeFree> transfeeFrees = transport.getTransfeeFrees();
                for (TransfeeFree transfeeFree : transfeeFrees) {
                    List<Area> freeCityList = transfeeFree.getFreeCityList();
                    for (Area freeCity : freeCityList) {
                        if (!Objects.equals(freeCity.getAreaId(), areaId)) {
                            continue;
                        }
                        //包邮方式 （0 满x件/重量/体积包邮 1满金额包邮 2满x件/重量/体积且满金额包邮）
                        if (transfeeFree.getFreeType() == 0 && piece >= transfeeFree.getPiece()) {
                            return 0.0;
                        } else if (transfeeFree.getFreeType() == 1 && productTotalAmount >= transfeeFree.getAmount()) {
                            return 0.0;
                        } else if (transfeeFree.getFreeType() == 2 && piece >= transfeeFree.getPiece() && productTotalAmount >= transfeeFree.getAmount()) {
                            return 0.0;
                        }
                    }
                }
            }

            //订单的运费项
            return getTransfee(areaId, transport, piece);
        }

        return 0.0;
    }

    private Double getTransfee(Long areaId, Transport transport, double piece) {
        Transfee transfee = null;
        List<Transfee> transfees = transport.getTransfees();
        for (Transfee dbTransfee : transfees) {
            // 将该商品的运费设置为默认运费
            if (transfee == null && CollectionUtil.isEmpty(dbTransfee.getCityList())) {
                transfee = dbTransfee;
            }
            // 如果在运费模板中的城市找到该商品的运费，则将该商品由默认运费设置为该城市的运费
            boolean isContainer = dbTransfee.getCityList().stream().anyMatch(area -> area.getAreaId().equals(areaId));
            if (isContainer) {
                transfee = dbTransfee;
                break;
            }
            // 如果在运费模板中的城市找到该商品的运费，则退出整个循环
            if (transfee != null && CollectionUtil.isNotEmpty(transfee.getCityList())) {
                break;
            }
        }

        // 如果无法获取到任何运费相关信息，则返回0运费
        if (transfee == null) {
            return 0.0;
        }
        // 产品的运费
        Double fee = transfee.getFirstFee();
        // 如果件数大于首件数量，则开始计算超出的运费
        if (piece > transfee.getFirstPiece()) {
            // 续件数量
            Double prodContinuousPiece = Arith.sub(piece, transfee.getFirstPiece());
            // 续件数量的倍数，向上取整
            Integer mulNumber = (int) Math.ceil(Arith.div(prodContinuousPiece, transfee.getContinuousPiece()));
            // 续件数量运费
            Double continuousFee = Arith.mul(mulNumber, transfee.getContinuousFee());
            fee = Arith.add(fee, continuousFee);
        }

        return fee == null ? 0.0 : fee;
    }

    /**
     * 去除没有店铺后的订单
     *
     * @param productItems 原用户所有的未处理订单
     * @return 去除没有店铺后的订单
     */
    private List<CollaborativePurchaseShopCartItemDto> removeNotTransPort(List<CollaborativePurchaseShopCartItemDto> productItems) {
        // 保存去掉没有运费模板重复的订单
        List<CollaborativePurchaseShopCartItemDto> resList = new ArrayList<>();

        for (CollaborativePurchaseShopCartItemDto productItem : productItems) {
            // 获取商品
            Product product = productService.getProductByProdId(productItem.getProdId(), I18nMessage.getDbLang());
            // 物流模板
            Product.DeliveryModeVO deliveryModeVO = Json.parseObject(product.getDeliveryMode(), Product.DeliveryModeVO.class);
            // 没有店铺配送的方式
            if (!deliveryModeVO.getHasShopDelivery()) {
                continue;
            }
            if (product.getDeliveryTemplateId() == null) {
                continue;
            }
            //找出该产品的运费项  运费模板
            Transport transport = transportService.getTransportAndAllItems(product.getDeliveryTemplateId());
            //商家把运费模板删除
            if (transport == null) {
                continue;
            }
            resList.add(productItem);
        }
        return resList;
    }


}
